//
// Created by 李文龙 on 2019/11/30.
//

#ifndef ASYNC_TASK_TIMER_H
#define ASYNC_TASK_TIMER_H

#include <atomic>
#include <memory>
#include <string>
#include <mutex>  // NOLINT
#include <future>  // NOLINT
#include <thread>  // NOLINT
#include <map>
#include "common.h"

NS_BEGIN


class MultitaskTimer final{
public:
    using Task = std::function<void()>;

    struct TaskItem{
        Task task;
        int interval_ms{0};
        std::string name;
    };

    MultitaskTimer(std::string const &tag = "");

    ~MultitaskTimer();

    void start();

    void addTimer(std::string const &name,Task f, int interval_ms);

    void removeTimer(std::string const &name);

    void stop();

    MultitaskTimer(const MultitaskTimer &) = delete;
    const MultitaskTimer& operator=(const MultitaskTimer&) = delete;
private:
    std::chrono::system_clock::time_point getFirstTime();
private:
    std::multimap<std::chrono::system_clock::time_point, TaskItem> task_queue_;
    std::atomic<bool> started_;
    std::atomic<bool> closed_;
    std::unique_ptr<std::thread> thread_;
    mutable std::mutex task_mutex_;
    std::condition_variable new_task_scheduled_;

    std::string tag_;
};

NS_END

#endif //ASYNC_TASK_POOL_TEST_TASK_QUEUE_H
